package com.ytktt.study.week5.task8;

import com.google.common.collect.Lists;
import com.ytktt.study.week5.task8.properties.Klass;
import com.ytktt.study.week5.task8.properties.School;
import com.ytktt.study.week5.task8.properties.Student;
import com.ytktt.study.week5.task8.properties.StudyProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Study自动配置类
 *
 * @author ytk
 */
@Configuration
@EnableConfigurationProperties(StudyProperties.class)
public class StudyAutoConfiguration {

    @Bean
    @ConditionalOnProperty(prefix = StudyProperties.PREFIX, name = "enabled", havingValue = "true")
    public School createSchool(StudyProperties studyProperties) {
        School school = studyProperties.getSchool();
        if (null == school.getKlass() || school.getKlass().isEmpty()) {
            throw new IllegalArgumentException("missing klass info");
        }
        return school;
    }

    @Bean
    @ConditionalOnMissingBean(School.class)
    public School defaultSchool() {
        // 创建默认学生
        Student student = new Student();
        student.setId(1);
        student.setName("default student");
        // 默认班级
        Klass klass = new Klass();
        klass.setStudents(Lists.newArrayList(student));
        // 默认学校
        School school = new School();
        school.setKlass(Lists.newArrayList(klass));
        return school;
    }

}
